package com.edu.DAO;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.edu.model.User;
import com.edu.Utils.DataSourceUtils;

public class UserDao {
	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	
	//存储信息到数据库
	public void save(User user) {
		Object[] params = {user.getUsername(),user.getSex(),user.getPassword(),user.getPhone(),user.getEmail()};
		try {
			qr.update("insert into user(username,sex,password,phone,email) values(?,?,?,?,?)",params);
			System.out.println("------------注册成功-----------");
			System.out.println(user.getUsername());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//根据用户名查询数据库
	public int getByUsername(String username) {
		long count = 0;
		try {
			count = (long)qr.query("select count(*) from user where username = ?", new ScalarHandler(),username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (int)count;
	}
	//根据用户名和密码查询数据库
	public User getUserByUserNP(String username,String password){
		String sql = "select * from user where username = ? and password = ?";
		User user = null;
		try {
			user = (User) qr.query(sql, new BeanHandler(User.class),username,password);
			if(user==null)
				System.out.println("===========");
		} catch (SQLException e) {
			e.printStackTrace();
		}

		System.out.println();
		return user;
	}
	
}
